package com.tools;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.List;
import java.util.zip.GZIPOutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.ByteArrayBuffer;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;

public class HttpInterface {
	public static String			tag					= "HttpConnectinterface";
	// public static String mmscUrl = "http://www.baidu.com/";
	public static String			mmsProxy			= "10.0.0.172";			// 代理地址
	public static String			mmsProt				= "80";					// 代理端口号
	private HttpListenerInterface	listenerInterface;
	public static final int			HTTP_POST_METHOD	= 1;
	public static final int			HTTP_GET_METHOD		= 2;
	
	// public static HttpInterface invoker() {
	// if (tools == null) {
	// tools = new HttpInterface();
	// }
	// return tools;
	// }
	public interface HttpListenerInterface {
		/***********************************************************
		 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
		 * @version time：2011-12-1 下午03:49:20
		 * @param progress
		 * @TODO 进度值，百分比
		 ***********************************************************/
		public void progressChanage(float progress);
	}
	
	public void setListener(HttpListenerInterface listenerInterface) {
		this.listenerInterface = listenerInterface;
	}
	
	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-15 下午07:07:46
	 * @param soTimeoutSec
	 * @param url
	 * @param method
	 * @param params
	 *            POST 方式链接，发送的内容 List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("to", to));
	 * @param proxyHost
	 *            代理IP地址 如果不使用代理，则传null
	 * @param proxyPort
	 *            代理服务器端口号
	 * @return
	 * @throws IOException
	 * @TODO 使用方法:InputStream in = entity.getContent() 使用后请销毁 entity.consumeContent();
	 ***********************************************************/
	public HttpEntity httpConnection(int soTimeoutSec, String url, int method, List<NameValuePair> nameValuePair, String proxyHost, int proxyPort) throws IOException {
		if (url == null) {
			throw new IllegalArgumentException("URL must not be null.");
		}
		
		HttpClient client = null;
		try {
			URI hostUrl = new URI(url);
			
			HttpRequest req = null;
			switch (method) {
				case HTTP_POST_METHOD:
					HttpPost post = new HttpPost(url);
					post.setEntity(new UrlEncodedFormEntity(nameValuePair));
					req = post;
				break;
				case HTTP_GET_METHOD:
					req = new HttpGet(url);
				break;
			}
			client = createHttpClient(soTimeoutSec);
			HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
			HttpParams params = client.getParams();
			if (proxyHost != null) {// 是否使用代理
				ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort));
			}
			req.setParams(params);
			HttpResponse response = client.execute(target, req);
			StatusLine status = response.getStatusLine();
			if (status.getStatusCode() != 200) { // HTTP 200 is success.
				throw new IOException("HTTP error: " + status.getReasonPhrase());
			}
			HttpEntity entity = response.getEntity();
			
			if (entity != null) {
				return entity;
			}
			
		} catch (Exception e) {
			if (listenerInterface != null) {
				listenerInterface.progressChanage(100);
			}
			e.printStackTrace();
		} finally {
			if (client != null) {
				// client.close();
				client = null;
			}
		}
		return null;
	}
	
	public String doNetwork(String addr, String requestContent) {
		
		String strResult = null;
		DataOutputStream out = null;
		OutputStream os = null;
		InputStream in = null;
		DataInputStream dism = null;
		HttpURLConnection conn = null;
		try {
			URL url = new URL(addr);
			conn = (HttpURLConnection) url.openConnection();
			
			conn.setRequestMethod("POST");
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(5000);
			conn.setRequestProperty("encode", "UTF-8"); // 编码方式
			conn.setRequestProperty("Content-Language", "en-CA");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.connect();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		try {
			os = conn.getOutputStream();
			out = new DataOutputStream(os);
			out.write(requestContent.getBytes("UTF-8"));
			int rc = conn.getResponseCode();
			
			if (rc == HttpURLConnection.HTTP_OK) {
				in = conn.getInputStream();
				int length = (int) conn.getContentLength();// .getLength();
				System.out.println("contentlength:" + length);
				ByteArrayBuffer baArrayBuffer = new ByteArrayBuffer(length + 10);
				byte msgData[] = new byte[2048];
				dism = new DataInputStream(in);
				int len = in.read(msgData);
				while (len != -1) {
					baArrayBuffer.append(msgData, 0, len);
					len = in.read(msgData);
				}
				
				System.out.println("msgData.length:" + msgData.length);
				strResult = new String(baArrayBuffer.toByteArray(), "UTF-8");// 设置编码方式为UTF-8,解决乱码的问题
				
			} else {
				strResult = "Error HttpURLConnection: " + rc;
			}
			return strResult;
		} catch (Exception ee) {
			ee.printStackTrace();
			return strResult;
		} finally {
			try {
				Log.e("Conn ", "result =" + strResult);
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
				if (os != null) {
					os.close();
				}
				if (dism != null) {
					dism.close();
				}
				if (conn != null) {
					conn.disconnect();
				}
				
				return strResult;
			} catch (Exception ioe) {
				ioe.printStackTrace();
			}
		}
	}
	
	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-14 下午03:07:08
	 * @param context
	 * @param soTimeoutSec
	 * @return
	 * @TODO 创建网络接口
	 ***********************************************************/
	public HttpClient createHttpClient(int soTimeoutSec) {
		HttpParams httpParams;
		httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, soTimeoutSec * 1000);
		HttpConnectionParams.setSoTimeout(httpParams, soTimeoutSec * 1000);
		HttpClientParams.setRedirecting(httpParams, true);
		HttpClient client = new DefaultHttpClient(httpParams);
		return client;
	}
	
	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time 2011-8-15 03:07:21
	 * @param context
	 * @return
	 * @TODO 网络CELLID
	 ***********************************************************/
	public String getCellId(Context context) {
		TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		int type = manager.getNetworkType();
		if (type == TelephonyManager.NETWORK_TYPE_GPRS || type == TelephonyManager.NETWORK_TYPE_EDGE) {
			GsmCellLocation cellLocation = ((GsmCellLocation) manager.getCellLocation());
			int cellCid = cellLocation.getCid();
			return "" + cellCid;
		} else return "not find cellCid";
	}
	
	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-22 上午11:49:51
	 * @param context
	 * @return
	 * @TODO 取得网络APN
	 ***********************************************************/
	public String getApn(Context context) {
		String apn = null;
		Uri uri = Uri.parse("content://telephony/carriers/preferapn");
		ContentResolver contentresolver = context.getContentResolver();
		Cursor cursor = contentresolver.query(uri, new String[] { "apn" }, null, null, null);
		cursor.moveToFirst();
		if (!cursor.isAfterLast()) {
			apn = cursor.getString(0);
		}
		return apn;
	}
	
	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-22 上午11:49:30
	 * @param context
	 * @return
	 * @TODO 是否为CMWAP网络 true:是， false:不是
	 ***********************************************************/
	public boolean isCmwap(Context context) {
		String apn = getApn(context);
		boolean ret = false;
		if (apn != null && apn.equals("cmwap")) {
			ret = true;
		}
		return ret;
	}
	
	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-10-21 上午11:24:53
	 * @param context
	 * @return
	 * @TODO Wifi是否可用 true:可用 false:不可用
	 ***********************************************************/
	public boolean isWifiEnabled(Context context) {
		try {
			boolean ret = false;
			if (context != null) {
				WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
				if (wifi.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
					ret = true;
				}
			}
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
	}
	
	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-10 上午10:32:39
	 * @param context
	 * @return
	 * @TODO 取得后一次记录的位置,若没有，刚返回NULL
	 ***********************************************************/
	public Location getLocation(Context context) {
		Location location = null;
		try {
			LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
			location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		} catch (Exception ex) {
			MyLog.e(ex);
		}
		return location;
	}
	
	/***
	 * 压缩数据
	 */
	public static AbstractHttpEntity getCompressedEntity(byte data[], ContentResolver resolver) throws IOException {
		AbstractHttpEntity entity;
		if (data.length < getMinGzipSize(resolver)) {
			entity = new ByteArrayEntity(data);
		} else {
			ByteArrayOutputStream arr = new ByteArrayOutputStream();
			OutputStream zipper = new GZIPOutputStream(arr);
			zipper.write(data);
			zipper.close();
			entity = new ByteArrayEntity(arr.toByteArray());
			entity.setContentEncoding("gzip");
		}
		return entity;
	}
	
	/***
	 * 取得最小压缩数据大小
	 */
	public static long getMinGzipSize(ContentResolver resolver) {
		return 256;
	}
}
